<template>
  <el-dialog
    v-model="visible"
    title="资产统计分析"
    width="1200px"
    :close-on-click-modal="false"
    top="5vh"
  >
    <div v-loading="loading" class="statistics-content">
      <!-- 筛选条件 -->
      <el-card class="filter-card" :body-style="{ padding: '15px' }">
        <el-form :model="filterForm" label-width="100px" inline>
          <el-form-item label="时间范围">
            <el-select v-model="filterForm.time_range" style="width: 150px">
              <el-option label="最近7天" value="7d" />
              <el-option label="最近30天" value="30d" />
              <el-option label="最近90天" value="90d" />
              <el-option label="最近1年" value="1y" />
            </el-select>
          </el-form-item>
          <el-form-item label="分组方式">
            <el-select v-model="filterForm.group_by" style="width: 150px">
              <el-option label="按风险等级" value="risk_level" />
              <el-option label="按状态" value="status" />
              <el-option label="按部门" value="department" />
              <el-option label="按场景类型" value="scene_type" />
            </el-select>
          </el-form-item>
          <el-form-item label="部门筛选">
            <el-select
              v-model="filterForm.department"
              placeholder="请选择部门"
              clearable
              filterable
              style="width: 150px"
            >
              <el-option
                v-for="dept in props.departmentOptions || []"
                :key="dept.value"
                :label="dept.label"
                :value="dept.value"
            />
            </el-select>
          </el-form-item>
          <el-form-item label="场景类型">
            <el-select
              v-model="filterForm.scene_type"
              style="width: 150px"
              clearable
            >
              <el-option label="财务敏感" value="financial" />
              <el-option label="人事信息" value="hr" />
              <el-option label="合同文件" value="contract" />
              <el-option label="技术文档" value="technical" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>

      <!-- 汇总统计 -->
      <el-card
        v-if="statisticsData?.total_assets !== undefined"
        class="summary-card"
        :body-style="{ padding: '15px' }"
      >
        <h3 class="card-title">📊 汇总统计</h3>
        <el-row :gutter="20">
          <el-col :span="6">
            <div class="stat-item">
              <div class="stat-label">总资产数</div>
              <div class="stat-value">
                {{ statisticsData.total_assets || 0 }}
              </div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-item">
              <div class="stat-label">高风险</div>
              <div class="stat-value danger">
                {{ getRiskLevelCount("high") }}
              </div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-item">
              <div class="stat-label">中风险</div>
              <div class="stat-value warning">
                {{ getRiskLevelCount("medium") }}
              </div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-item">
              <div class="stat-label">低风险</div>
              <div class="stat-value success">
                {{ getRiskLevelCount("low") }}
              </div>
            </div>
          </el-col>
        </el-row>
      </el-card>

      <!-- 按风险等级统计 -->
      <el-card
        v-if="
          statisticsData?.by_risk_level &&
          Object.keys(statisticsData.by_risk_level).length > 0
        "
        class="group-card"
        :body-style="{ padding: '15px' }"
      >
        <h3 class="card-title">📈 按风险等级统计</h3>
        <el-table :data="riskLevelData" border>
          <el-table-column prop="name" label="风险等级" min-width="150">
            <template #default="{ row }">
              <el-tag
                v-if="row.key === 'critical' || row.key === 'high'"
                type="danger"
                size="small"
              >
                {{ row.name }}
              </el-tag>
              <el-tag
                v-else-if="row.key === 'medium'"
                type="warning"
                size="small"
              >
                {{ row.name }}
              </el-tag>
              <el-tag v-else type="success" size="small">
                {{ row.name }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column
            prop="count"
            label="数量"
            width="120"
            align="center"
          />
          <el-table-column
            prop="percentage"
            label="占比"
            width="120"
            align="center"
          >
            <template #default="{ row }"> {{ row.percentage }}% </template>
          </el-table-column>
        </el-table>
      </el-card>

      <!-- 按审核状态统计 -->
      <el-card
        v-if="
          statisticsData?.by_review_status &&
          Object.keys(statisticsData.by_review_status).length > 0
        "
        class="group-card"
        :body-style="{ padding: '15px' }"
      >
        <h3 class="card-title">📋 按审核状态统计</h3>
        <el-table :data="reviewStatusData" border>
          <el-table-column prop="name" label="审核状态" min-width="150">
            <template #default="{ row }">
              <el-tag :type="getStatusType(row.key)" size="small">
                {{ row.name }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column
            prop="count"
            label="数量"
            width="120"
            align="center"
          />
          <el-table-column
            prop="percentage"
            label="占比"
            width="120"
            align="center"
          >
            <template #default="{ row }"> {{ row.percentage }}% </template>
          </el-table-column>
        </el-table>
      </el-card>

      <!-- 按部门统计 -->
      <el-card
        v-if="
          statisticsData?.by_department &&
          Object.keys(statisticsData.by_department).length > 0
        "
        class="group-card"
        :body-style="{ padding: '15px' }"
      >
        <h3 class="card-title">🏢 按部门统计</h3>
        <el-table :data="departmentData" border>
          <el-table-column prop="name" label="部门名称" min-width="200" />
          <el-table-column
            prop="count"
            label="数量"
            width="120"
            align="center"
          />
          <el-table-column
            prop="percentage"
            label="占比"
            width="120"
            align="center"
          >
            <template #default="{ row }"> {{ row.percentage }}% </template>
          </el-table-column>
        </el-table>
      </el-card>

      <!-- 按场景统计 -->
      <el-card
        v-if="
          statisticsData?.by_scene &&
          Object.keys(statisticsData.by_scene).length > 0
        "
        class="group-card"
        :body-style="{ padding: '15px' }"
      >
        <h3 class="card-title">🎯 按场景统计</h3>
        <el-table :data="sceneData" border>
          <el-table-column prop="name" label="场景名称" min-width="200" />
          <el-table-column
            prop="count"
            label="数量"
            width="120"
            align="center"
          />
          <el-table-column
            prop="percentage"
            label="占比"
            width="120"
            align="center"
          >
            <template #default="{ row }"> {{ row.percentage }}% </template>
          </el-table-column>
        </el-table>
      </el-card>

      <!-- 按文件类型统计 -->
      <el-card
        v-if="
          statisticsData?.by_file_type &&
          Object.keys(statisticsData.by_file_type).length > 0
        "
        class="group-card"
        :body-style="{ padding: '15px' }"
      >
        <h3 class="card-title">📄 按文件类型统计</h3>
        <el-table :data="fileTypeData" border>
          <el-table-column prop="name" label="文件类型" min-width="150">
            <template #default="{ row }">
              <span v-if="row.key === 'unknown'">未知类型</span>
              <span v-else>{{ row.key.toUpperCase() }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="count"
            label="数量"
            width="120"
            align="center"
          />
          <el-table-column
            prop="percentage"
            label="占比"
            width="120"
            align="center"
          >
            <template #default="{ row }"> {{ row.percentage }}% </template>
          </el-table-column>
        </el-table>
      </el-card>

      <el-empty
        v-if="!loading && !statisticsData"
        description="暂无统计数据，请选择筛选条件后查询"
      />
    </div>
    <!-- 
    <template #footer>
      <el-button @click="handleCancel">关闭</el-button>
      <el-button
        type="primary"
        @click="handleExport"
        :disabled="!statisticsData"
      >
        导出统计报告
      </el-button>
    </template> -->
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from "vue";
import { ElMessage } from "element-plus";
import { getPanAssetsStatistics } from "../../../servers";

const props = defineProps({
  modelValue: { type: Boolean, default: false },
  departmentOptions: {
    type: Array as () => Array<{ label: string; value: string }>,
    default: () => [],
  },
});

const emit = defineEmits<{
  (e: "update:modelValue", value: boolean): void;
}>();

const visible = computed({
  get: () => props.modelValue,
  set: (value: boolean) => emit("update:modelValue", value),
});

const loading = ref(false);
const statisticsData = ref<any>(null);

const filterForm = reactive({
  time_range: "30d" as "7d" | "30d" | "90d" | "1y",
  group_by: "risk_level" as
    | "risk_level"
    | "status"
    | "department"
    | "scene_type",
  department: "",
  scene_type: "",
});

// 监听弹窗打开，自动查询
watch(visible, (newVal) => {
  if (newVal) {
    handleSearch();
  } else {
    statisticsData.value = null;
  }
});

// 格式化文件大小
const formatSize = (bytes: number): string => {
  if (!bytes) return "0 B";
  if (bytes < 1024) return `${bytes} B`;
  if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(2)} KB`;
  if (bytes < 1024 * 1024 * 1024)
    return `${(bytes / (1024 * 1024)).toFixed(2)} MB`;
  return `${(bytes / (1024 * 1024 * 1024)).toFixed(2)} GB`;
};

// 获取风险等级数量
const getRiskLevelCount = (level: string): number => {
  if (!statisticsData.value?.by_risk_level) return 0;
  return statisticsData.value.by_risk_level[level] || 0;
};

// 获取状态类型
const getStatusType = (
  status: string
): "success" | "warning" | "danger" | "info" => {
  const typeMap: Record<string, "success" | "warning" | "danger" | "info"> = {
    pending: "info",
    confirmed: "success",
    ignored: "warning",
  };
  return typeMap[status] || "info";
};

// 将对象转换为数组并计算百分比
const convertToArray = (obj: Record<string, number>, total: number) => {
  if (!obj || total === 0) return [];
  return Object.entries(obj).map(([key, count]) => ({
    key,
    name: getGroupNameText(key),
    count,
    percentage: ((count / total) * 100).toFixed(1),
  }));
};

// 获取分组名称文本
const getGroupNameText = (name: string): string => {
  const textMap: Record<string, string> = {
    critical: "极高风险",
    high: "高风险",
    medium: "中风险",
    low: "低风险",
    pending: "待处理",
    confirmed: "已确认",
    ignored: "已忽略",
    financial: "财务敏感",
    hr: "人事信息",
    contract: "合同文件",
    technical: "技术文档",
    unknown: "未知类型",
  };
  return textMap[name] || name;
};

// 计算统计数据
const riskLevelData = computed(() => {
  if (!statisticsData.value?.by_risk_level) return [];
  return convertToArray(
    statisticsData.value.by_risk_level,
    statisticsData.value.total_assets || 0
  );
});

const reviewStatusData = computed(() => {
  if (!statisticsData.value?.by_review_status) return [];
  return convertToArray(
    statisticsData.value.by_review_status,
    statisticsData.value.total_assets || 0
  );
});

const departmentData = computed(() => {
  if (!statisticsData.value?.by_department) return [];
  return convertToArray(
    statisticsData.value.by_department,
    statisticsData.value.total_assets || 0
  );
});

const sceneData = computed(() => {
  if (!statisticsData.value?.by_scene) return [];
  return convertToArray(
    statisticsData.value.by_scene,
    statisticsData.value.total_assets || 0
  );
});

const fileTypeData = computed(() => {
  if (!statisticsData.value?.by_file_type) return [];
  return convertToArray(
    statisticsData.value.by_file_type,
    statisticsData.value.total_assets || 0
  );
});

// 查询统计
const handleSearch = async () => {
  loading.value = true;
  try {
    const params: any = {
      time_range: filterForm.time_range,
      group_by: filterForm.group_by,
    };

    if (filterForm.department) {
      params.department = filterForm.department;
    }
    if (filterForm.scene_type) {
      params.scene_type = filterForm.scene_type;
    }

    const result = await getPanAssetsStatistics(params);

    statisticsData.value = result.data;
  } catch (error: any) {
    ElMessage.error(error?.message || "获取统计数据失败");
  } finally {
    loading.value = false;
  }
};

// 重置
const handleReset = () => {
  filterForm.time_range = "30d";
  filterForm.group_by = "risk_level";
  filterForm.department = "";
  filterForm.scene_type = "";
  handleSearch();
};

// 导出统计报告
const handleExport = () => {
  ElMessage.info("导出统计报告功能开发中");
};

// 取消
const handleCancel = () => {
  emit("update:modelValue", false);
};
</script>

<style scoped lang="scss">
.statistics-content {
  max-height: 70vh;
  overflow-y: auto;
  padding-right: 10px;
}

.filter-card,
.summary-card,
.group-card,
.trend-card {
  margin-bottom: 20px;
}

.card-title {
  font-size: 16px;
  font-weight: 500;
  margin: 0 0 15px 0;
  color: #303133;
}

.stat-item {
  text-align: center;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;

  .stat-label {
    font-size: 14px;
    color: #909399;
    margin-bottom: 8px;
  }

  .stat-value {
    font-size: 24px;
    font-weight: 600;
    color: #303133;

    &.danger {
      color: #f5222d;
    }

    &.warning {
      color: #faad14;
    }

    &.success {
      color: #52c41a;
    }
  }
}
</style>
